package xyz.xpman.prisonerfitness.kit;

import android.annotation.SuppressLint;
import android.view.View;
import android.view.ViewTreeObserver;

import org.jetbrains.annotations.NotNull;

import java.util.function.Consumer;

public class ViewKit {

    private ViewKit() { }


    public interface CallBack {
        void callBack(int height, int width);
    }

    public static void getSize(@NotNull final View view,
                               @NotNull final CallBack callback) {
        final int visibility = view.getVisibility();

        if (View.GONE == visibility) {
            // 都一样，为了获得组件高度（让系统计算下，GONE模式下不会计算高宽属性）
            // view.setVisibility(View.VISIBLE);
            view.setVisibility(View.INVISIBLE);
        }

        ViewTreeObserver.OnPreDrawListener onPreDrawListener;
        final Consumer<ViewTreeObserver.OnPreDrawListener> remove = listener ->
                view.getViewTreeObserver().removeOnPreDrawListener(listener);

        onPreDrawListener = new ViewTreeObserver.OnPreDrawListener() {
            @SuppressLint("NewApi")
            @Override
            public boolean onPreDraw() {
                int height = view.getMeasuredHeight();
                int width = view.getMeasuredWidth();

                // 还原visibility
                view.setVisibility(visibility);

                // 删除这个监听器
                remove.accept(this);

                // 回调
                callback.callBack(height, width);
                return true;
            }
        };

        view.getViewTreeObserver().addOnPreDrawListener(onPreDrawListener);
    }

}
